package com.jhhc.StormSurgeForecast.Calculate.Controller;

import cn.hutool.core.lang.UUID;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.TimeUtil;
import com.jhhc.StormSurgeForecast.Calculate.BO.CenterUrl;
import com.jhhc.StormSurgeForecast.Calculate.BO.ModelConfig;
import com.jhhc.StormSurgeForecast.Calculate.util.CalUtil;
import com.jhhc.StormSurgeForecast.Calculate.util.DownloadUtil;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.FBC.BDMS_FBC_OCEANMODEL_B;
import com.jhhc.StormSurgeForecast.StormSurge.Service.BDMS_FBC_ASTROTD_AService;
import com.jhhc.StormSurgeForecast.StormSurge.Service.BDMS_FBC_OCEANMODEL_BService;
import com.jhhc.utils.JsonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author LYQ
 */
@RestController
@RequestMapping(value = "StormSurgeForcast/Calculate")
@Log4j2
public class TideModelController {

    @Autowired
    private BDMS_FBC_OCEANMODEL_BService bService;

    @Autowired
    private BDMS_FBC_ASTROTD_AService bdms_fbc_astrotd_aService;

    @Autowired
    private ModelConfig modelConfig;

   // @Value("${key}")
    String key;
    @RequestMapping(value = "/Forecast/TideRun",method = RequestMethod.GET, headers = "Accept=application/json")
    public JsonResult tideRun(@RequestParam Integer year,@RequestParam Integer projectId,
                              @RequestParam String modelId,@RequestParam boolean area){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatusCode(200);
        jsonResult.setSucceeded(true);
        String jobId = "";//作业id
        String jobStatus = "";//作业状态
        String code = "";//上传文件状态
        CalUtil calUtil = new CalUtil();
        //查询对应模型
        BDMS_FBC_OCEANMODEL_B bdmsFbcOceanmodelB = bService.getModelInfo(projectId, modelId);
        String token = calUtil.getToken(modelConfig);//获取token
        if (token == null || "".equals(token)) {
            jsonResult.setRemark("获取token失败");
            return jsonResult;
        }
        CenterUrl centerUrl = calUtil.getCenter(token,modelConfig);//获取授权区域地址center
        DownloadUtil downloadUtil = new DownloadUtil();
        String modelPath = modelConfig.getUserpathname() + "model/" + bdmsFbcOceanmodelB.getFoldernm();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String startTime = year + "-01-02 00:00:00";
        String endTime = year + "-12-31 23:00:00";
        String timeS = startTime;
        TimeUtil timeUtil = new TimeUtil();
        try {
            switch (modelId){
                case "JSCoastTide"://江苏沿海天文潮模型
                    while (format.parse(timeS).compareTo(format.parse(endTime)) <= 0){
                        UUID uuid = UUID.randomUUID();
                        String localPath = modelConfig.getLocalPath() + File.separator + uuid;
                        String cschemePath = "/work/home/ykg83787340/model/caltmp/" + uuid;
                        String linuxPath = cschemePath + "/" + bdmsFbcOceanmodelB.getFoldernm();
                        String workPath = cschemePath + "/" + bdmsFbcOceanmodelB.getFoldernm();
                        jobId = calUtil.createFolder(centerUrl.getHpcUrl(), token, cschemePath, modelConfig);
                        jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token, jobId);
                        //查询作业状态
                        while (!"statC".equals(jobStatus)) {
                            try {
                                TimeUnit.SECONDS.sleep(2);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                System.out.println("线程暂停异常");
                            }
                            jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token, jobId);
                            System.out.println("等待作业完成中...");
                        }
                        jobId = calUtil.copyFolder(centerUrl.getHpcUrl(), token, cschemePath, modelConfig, modelPath);
                        jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token, jobId);
                        //查询作业状态
                        while (!"statC".equals(jobStatus)) {
                            try {
                                TimeUnit.SECONDS.sleep(2);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                System.out.println("线程暂停异常");
                            }
                            jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token, jobId);
                            System.out.println("等待作业完成中...");
                        }
                        System.out.println(startTime);
                        System.out.println(timeS);
                        if (format.parse(timeS).compareTo(format.parse(endTime)) != 0) {
                            timeS = timeUtil.dateAddDay(startTime,30);
                            //生成nhup1.txt文件
                            File nhup = calUtil.createNhup1File(startTime, localPath, timeS,
                                    "0.9", area, bdmsFbcOceanmodelB);
                            //上传nhup1.txt文件
                            calUtil.fileUpload(centerUrl.getEfileUrl(), token, nhup, linuxPath);
                            jobId = calUtil.modelCalculate(centerUrl.getHpcUrl(), token, modelConfig, workPath);
                            jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token,jobId);
                            while (!Objects.equals(jobStatus,"statC")){
                                try {
                                    TimeUnit.SECONDS.sleep(100);
                                    jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token,jobId);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                    System.out.println("异步线程异常");
                                }
                            }
                            //下载文件入库
                            downloadUtil.downloadFort63(centerUrl.getEfileUrl(),token, linuxPath,localPath);
                            String path = localPath + File.separator + "fort.63";
                            bdms_fbc_astrotd_aService.astronomicalTideInsertA(
                                        localPath,"230103",startTime);
                        }else {
                            //生成nhup1.txt文件
                            File nhup = calUtil.createNhup1File(startTime, localPath, timeS,
                                    "0.9", area, bdmsFbcOceanmodelB);
                            //上传nhup1.txt文件
                            code = calUtil.fileUpload(centerUrl.getEfileUrl(), token, nhup, linuxPath);
                            jobId = calUtil.modelCalculate(centerUrl.getHpcUrl(), token, modelConfig, workPath);
                            jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token,jobId);
                            while (!Objects.equals(jobStatus,"statC")){
                                try {
                                    TimeUnit.SECONDS.sleep(100);
                                    jobStatus = calUtil.queryJobs(centerUrl.getHpcUrl(), token,jobId);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                    System.out.println("异步线程异常");
                                }
                            }
                            //下载文件入库
                            downloadUtil.downloadFort63(centerUrl.getEfileUrl(),token, linuxPath,localPath);
                            bdms_fbc_astrotd_aService.astronomicalTideInsertA(
                                        localPath,"230103",startTime);
                            break;
                        }
                        //下一次循环,更新时间
                        startTime = timeUtil.dateAddHour(timeS,1);
                        if (timeUtil.differenceValue(timeS,endTime) < 30) {
                            timeS = endTime;
                        }
                    }
                    break;
                case "":
                    break;
                default:
                    break;
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return jsonResult;
    }
}
